package com.charley.icloud.common.response.utils;

import com.charley.icloud.common.utils.SpringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应结果封装类
 *   提供了发送文本、json、xml等内容方格式的法
 * */
@Slf4j
public class ResponseContentTypeUtil {

    /**
     * 发送文本。使用UTF-8编码。
     * @param response HttpServletResponse
     * @param text     发送的字符串
     */
    public static void renderText(HttpServletResponse response, String text) {
        render(response, "text/plain;charset=UTF-8", text);
    }

    /**
     * 发送json。使用UTF-8编码。
     * @param response HttpServletResponse
     * @param obj     内容
     */
    public static void renderJson(HttpServletResponse response, Object obj) {
        try {
            ObjectMapper objectMapper = SpringUtils.getBean(ObjectMapper.class) ;
            render(response, "application/json;charset=UTF-8", objectMapper.writeValueAsString(obj));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 错误处理响应方法 Json格式
     * @param response HttpServletResponse
     * @param obj 内容
     * @param httpStatus 响应结果状态码
     * */
    public static void renderJsonError(HttpServletResponse response, Object obj ,int httpStatus) {
        try {
            response.setStatus(httpStatus); // 设置响应状态码
            ObjectMapper objectMapper = SpringUtils.getBean(ObjectMapper.class) ;
            render(response, "application/json;charset=UTF-8", objectMapper.writeValueAsString(obj));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 发送xml。使用UTF-8编码。
     * @param response HttpServletResponse
     * @param text     发送的字符串
     */
    public static void renderXml(HttpServletResponse response, String text) {
        render(response, "text/xml;charset=UTF-8", text);
    }

    /**
     * 发送内容。使用UTF-8编码。
     * @param response HttpServletResponse
     * @param contentType 自定义文本内容格式
     * @param text 发送的字符串
     */
    public static void render(HttpServletResponse response, String contentType,String text) {
        // 设置响应类型
        response.setContentType(contentType);
        // 设置响应头
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try (PrintWriter out = response.getWriter())  {
            out.write(text);
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
